# -*- coding: utf-8 -*-
import json
import math
import re

import scrapy

from xmly.items import XmlyItem


class BbbsSpider(scrapy.Spider):
    name = 'bbbs'
    allowed_domains = ['m.ximalaya.com']
    base_url = "https://m.ximalaya.com/m-revision/common/album/queryAlbumTrackRecordsByPage?albumId=%s&page={page}&pageSize=10&asc=true"

    # start_urls = [
    #     base_url.format(page=1)
    # ]

    def __init__(self, albumId, *args, **kwargs):
        self.base_url = self.base_url % albumId

    def start_requests(self):
        yield scrapy.Request(url=self.base_url.format(page=1))

    def parse(self, response):
        id, totalCount, page, pageSize, trackDetailInfos = json.loads(response.text)["data"].values()
        for item in trackDetailInfos:
            track = XmlyItem()
            track["id"] = item["trackInfo"]["id"]
            track["albumId"] = item["trackInfo"]["albumId"]
            # title='【民间故事】多多学习知识：傻乎乎的小狼【宝宝巴士故事】'
            # track["title"] = re.search(r'】(.*)【', item["trackInfo"]["title"]).group(1)
            track["title"] = item["trackInfo"]["title"]
            track["path"] = item["trackInfo"]["playPath"]
            track["file_urls"] = [track["path"]]
            yield track
        if page == 1:
            for i in range(2, math.ceil(totalCount / pageSize)):
                yield scrapy.Request(url=self.base_url.format(page=i), callback=self.parse)
